package cn.itsource.system.service.impl;

import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.utils.PageResult;
import cn.itsource.system.domain.Role;
import cn.itsource.system.mapper.RoleMapper;
import cn.itsource.system.service.IRoleService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Transactional
    @Override
    public void add(Role role) {
        super.add(role);

        if (role.getMenus().size() > 0){
            roleMapper.addRoleMenu(role);
        }
        if (role.getPermissions().size() > 0){
            roleMapper.addRolePermissions(role);
        }
    }

    @Override
    @Transactional
    public void update(Role role) {
        super.update(role);
        //先删除在添加
        roleMapper.delRoleMenuId(role.getId());
        roleMapper.delRolePermissionsId(role.getId());

        if (role.getMenus().size() > 0){
            roleMapper.addRoleMenu(role);
        }
        if (role.getPermissions().size() > 0){
            roleMapper.addRolePermissions(role);
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        //删除角色的权限和菜单-先删除关联信息，防止外键约束异常。
        roleMapper.delRoleMenuId(id);
        roleMapper.delRolePermissionsId(id);
        super.delete(id);
    }

    @Override
    public void patchdel(Long[] ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    @Override
    public PageResult<Role> queryPage(BaseQuery query) {
        PageResult<Role> pageResult = super.queryPage(query);
        List<Role> roles = pageResult.getList();
        for (Role role : roles) {
            List<Long> menus = roleMapper.findMenuRoleId(role.getId());
            role.setMenus(menus);
            List<Long> permissions = roleMapper.findPermissionsRoleId(role.getId());
            role.setPermissions(permissions);
        }
    return pageResult;
    }
}
